package com.nitty.cash.loop.ui.presenter

import android.graphics.Color
import android.view.View
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.lib.common.permission.Permission
import com.nitty.cash.loop.NittyApp
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonPresenter
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.dialog.NittyTipsDialog
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONArray
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/28 15:41
 * @Annotation：权限页面
 */
class PermissionPresenter(private val iView: IViewContract.IPermissionView): CommonPresenter(iView) {

    private var permissionList: ArrayList<JSONObject>? = null
    //当前权限下标
    var curtIndex = 0

    /**
     * 获取权限列表
     */
    fun loadUserPermissionListAction(){
        permissionList = arrayListOf()
        val permissionArray = NittyConfigsHelper.getNittyPermissionsLaunch()
        if (permissionArray.size > 0){
            //手动添加一条Applist
            permissionArray.add(NittyApp.app.getString(R.string.permission_app_list_launch_title))
            for (i in 0..<permissionArray.size){
                val permission = permissionArray[i]
                permissionList!!.add(formatUserPermissionItem(permission))
            }
        }
        iView.showPermissionList(permissionList!!)

        curtIndex = getUserPermissionIndex()
        setUserPermissionStatus()
    }

    /**
     * 下一个
     */
    fun onUserPermissionNextAction(){
        //全部同意
        if (isUserPermissionAgreeAll()){
            iView.showPermissionSuccess()
            return
        }
        //全部完成（拒绝+同意） -> 展示拒绝的权限
        if (curtIndex == permissionList!!.size){
            iView.showPermissionPage(getUserPermissionIndex())
            return
        }
        curtIndex++
        iView.showPermissionPage(curtIndex)
    }

    /**
     * 拒绝权限
     */
    fun onUserPermissionDenyClick(){
        val item = permissionList!![curtIndex]
        item.put("isAgree",false)
        item.put("isClick",true)
        iView.showPermissionBanned()
        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_DENY,item.optString("permission"))

        onUserPermissionCheckPageClick(getUserPermissionIndex())
    }

    /**
     * 同意
     */
    fun onUserPermissionAgreeClick(){
        val item = permissionList!![curtIndex]
        val tipsDialog = NittyTipsDialog(iView.getAct(),item.optString("permission"),object : NittyTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btnDialogTipsOK -> {
                        hasRequestUserPermissions(item)
                        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
                    }
                    R.id.btnDialogTipsCancel -> {
                        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.setTitleText(iView.getAct().getString(R.string.dialog_tips))
        if (item.optBoolean("isSystem")){
            tipsDialog.setTipsText(iView.getAct().getString(R.string.permission_agree_tips))
        } else {
            tipsDialog.setTipsText(iView.getAct().getString(R.string.permission_read_tips))
        }

        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_AGREE,item.optString("permission"))
    }

    /**
     * 切换Page
     */
    fun onUserPermissionCheckPageClick(index: Int){
        curtIndex = index
        setUserPermissionStatus()
    }

    /**
     * 已拒绝按钮
     */
    fun onUserPermissionBannedClick(){
        val item = permissionList!![curtIndex]
        CommonPermissions.startPermissionActivity(iView.getAct(),item.optString("permission"))
        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_BANNED,item.optString("permission"))
    }

    /**
     * onResume
     */
    fun onUserPermissionResume(){
        curtIndex = getUserPermissionIndex()
        setUserPermissionStatus()
    }

    /**
     * 显示权限
     */
    private fun setUserPermissionStatus(){
        //全部允许
        if (isUserPermissionAgreeAll()){
            iView.showPermissionSuccess()
            return
        }
        val item = permissionList!![curtIndex]
        iView.showPermissionPage(curtIndex)

        var isShowAgree = false
        //系统权限
        if (item.optBoolean("isSystem")){
            //是否已获得权限
            val isGranted = CommonPermissions.isGranted(iView.getAct(),item.optString("permission"))
            //已获得权限
            if (isGranted){
                isShowAgree = true
            }
        } else {//非系统权限
            if (item.optBoolean("isClick",false) && item.optBoolean("isAgree",false)){
                isShowAgree = true
            }
        }
        if (isShowAgree){
            item.put("isAgree",true)
            item.put("isClick",true)
            iView.showPermissionAuthorized()
            return
        }

        if (item.optBoolean("isClick",false) && !item.optBoolean("isAgree",false)){
            iView.showPermissionBanned()
            return
        }
        iView.showPermissionNotObtained()
    }

    /**
     * 是否全部已授权
     */
    private fun isUserPermissionAgreeAll(): Boolean{
        var isAgreeAll = true
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //已同意跳过
                if (item.optBoolean("isAgree")){
                    continue
                }

                var isAgree = false
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    //是否是系统权限
                    if (item.optBoolean("isSystem")){
                        if (CommonPermissions.isGranted(iView.getAct(),item.optString("permission"))){
                            isAgree = true
                        }
                    }
                } else {
                    if (item.optBoolean("isClick")){
                        isAgree = true
                    }
                }

                if (!isAgree){
                    isAgreeAll = false
                    break
                }
            }
        }
        return isAgreeAll
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getUserPermissionIndex(): Int{
        var index = curtIndex
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!CommonPermissions.isGranted(iView.getAct(),item.optString("permission"))){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick",false)){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 获取所有权限列表
     */
    fun getUserPermissionList(): ArrayList<JSONObject>{
        return permissionList!!
    }

    /**
     * 申请权限
     */
    fun hasRequestUserPermissions(item: JSONObject){
        //非系统权限
        if (!item.optBoolean("isSystem")){
            item.put("isAgree",true)
            item.put("isClick",true)
            iView.showPermissionAuthorized()
            //验证是否全部已同意
            if (isUserPermissionAgreeAll()){
                iView.showPermissionSuccess()
                return
            }
            curtIndex = getUserPermissionIndex()
            setUserPermissionStatus()
            return
        }

        val permission = item.optString("permission")
        CommonPermissions.with(iView.getAct())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        item.put("isAgree",true)
                        item.put("isClick",true)
                        addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_AGREE,permission)
                        iView.showPermissionAuthorized()
                        //验证是否全部已同意
                        if (isUserPermissionAgreeAll()){
                            iView.showPermissionSuccess()
                            return
                        }
                        curtIndex = getUserPermissionIndex()
                        setUserPermissionStatus()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    item.put("isAgree",false)
                    item.put("isClick",true)
                    //不在询问
                    if (doNotAskAgain){
                        CommonPermissions.startPermissionActivity(iView.getAct(),permission)
                        iView.showPermissionBanned()
                        return
                    }
                    addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_DENY,permission)
                    iView.showPermissionBanned()
                    //验证是否全部已同意
                    if (isUserPermissionAgreeAll()){
                        iView.showPermissionSuccess()
                        return
                    }
                    curtIndex = getUserPermissionIndex()
                    setUserPermissionStatus()
                }
            })
    }

    /**
     * 拼装权限Item
     */
    private fun formatUserPermissionItem(permission: String): JSONObject{
        var item = JSONObject()
        item.put("permission",permission)
        item.put("isAgree",false)
        item.put("isClick",false)
        item.put("isSystem",true)
        when(permission){
            Permission.READ_SMS -> {
                item.put("isSystem",false)
                item.put("isMust",false)
                item.put("icon", R.mipmap.nitty_permission_sms_icon)
                item.put("title",getString(R.string.permission_sms_launch_title))
                item.put("titleColor", Color.parseColor("#FF000000"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",getString(R.string.permission_sms_why))
                obj1.put("des",getString(R.string.permission_sms_why_desc))
                msgArray.put(obj1)

                val obj2 = JSONObject()
                obj2.put("title",getString(R.string.permission_sms_do))
                obj2.put("des",getString(R.string.permission_sms_do_desc))
                msgArray.put(obj2)

                val obj3 = JSONObject()
                obj3.put("title",getString(R.string.permission_sms_data_security))
                obj3.put("des",getString(R.string.permission_sms_data_security_desc))
                msgArray.put(obj3)

                val obj4 = JSONObject()
                obj4.put("title",getString(R.string.permission_sms_regarding))
                obj4.put("des",getString(R.string.permission_sms_regarding_desc))
                msgArray.put(obj4)

                item.put("msgList",msgArray)
            }
            Permission.READ_PHONE_STATE -> {
                item.put("isMust",true)
                item.put("icon",R.mipmap.nitty_permission_phone_state_icon)
                item.put("title",getString(R.string.permission_phone_state_title))
                item.put("titleColor", Color.parseColor("#FF000000"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",getString(R.string.permission_phone_state_why))
                obj1.put("des",getString(R.string.permission_phone_state_why_desc))
                msgArray.put(obj1)

                val obj2 = JSONObject()
                obj2.put("title",getString(R.string.permission_phone_state_collected))
                obj2.put("des",getString(R.string.permission_phone_state_collected_desc))
                msgArray.put(obj2)

                val obj3 = JSONObject()
                obj3.put("title",getString(R.string.permission_phone_state_purpose))
                obj3.put("des",getString(R.string.permission_phone_state_purpose_desc))
                msgArray.put(obj3)

                item.put("msgList",msgArray)
            }
            NittyApp.app.getString(R.string.permission_app_list_launch_title) -> {
                item.put("isSystem",false)
                item.put("isMust",false)
                item.put("icon", R.mipmap.nitty_permission_applist_icon)
                item.put("title",getString(R.string.permission_app_list_launch_title))
                item.put("titleColor", Color.parseColor("#FF000000"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",getString(R.string.permission_app_list_why))
                obj1.put("des",getString(R.string.permission_app_list_why_desc))
                msgArray.put(obj1)

                val obj2 = JSONObject()
                obj2.put("title",getString(R.string.permission_app_list_do))
                obj2.put("des",getString(R.string.permission_app_list_do_desc))
                msgArray.put(obj2)

                val obj3 = JSONObject()
                obj3.put("title",getString(R.string.permission_app_list_collect))
                obj3.put("des",getString(R.string.permission_app_list_collect_desc))
                msgArray.put(obj3)

                val obj4 = JSONObject()
                obj4.put("title",getString(R.string.permission_app_list_data_safety))
                obj4.put("des",getString(R.string.permission_app_list_data_safety_desc))
                msgArray.put(obj4)

                item.put("msgList",msgArray)
            }
        }
        return item
    }

}